package com.yzmoney.wechat.action;

import com.yzmoney.common.constant.Constants;
import com.yzmoney.common.constant.PropertyUtils;
import com.yzmoney.common.util.JDKStackTrace;
import com.yzmoney.common.util.MessageUtil;
import com.yzmoney.wechat.service.WechatCommonMsgReceiveService;
import com.yzmoney.wechat.service.WechatEventReceiveService;
import com.yzmoney.wechat.service.WechatVerifyService;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

@Controller()
@RequestMapping(value = "/qyh")
public class QYHAction {
    private static Logger logger = Logger.getLogger(QYHAction.class);

    @Autowired
    private WechatVerifyService wechatVerifyService;

    @Autowired
    private WechatEventReceiveService wechatEventReceiveService;

    @Autowired
    private WechatCommonMsgReceiveService wechatCommonMsgReceiveService;

    private static String token = PropertyUtils.getValue("TOKEN", "", Constants.GZH_PATH);

    @RequestMapping(value = "/service")
    public ModelAndView service(HttpServletRequest request, HttpServletResponse response) {
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");

        logger.info(Constants.LOGPRIFIX + "token=" + token + ",signature=" + signature + ",timestamp=" + timestamp + ",nonce=" + nonce);

        ModelAndView nextMAV = null;
        //消息真实性未通过
        if (!wechatVerifyService.checkSignature(token, signature, timestamp, nonce)) {
            nextMAV = new ModelAndView("forward:/gzh/warn.do");
        } else {
            if (echostr != null) { //转向验证url有效性
                nextMAV = new ModelAndView("forward:/gzh/urlValidVerify.do");
            } else {
                try {
                    InputStream in = request.getInputStream();
                    Document docXml = new SAXReader().read(in);
                    Element rootElement = docXml.getRootElement();
                    logger.info(Constants.LOGPRIFIX + "接收微信信息. xml=" + MessageUtil.parseXml(docXml));
                    if (rootElement.element("Event") != null) {
                        //接收事件消息
                        nextMAV = wechatEventReceiveService.receiveEvent(docXml);
                    } else if (rootElement.element("Recognition") != null) {
                        //接收语音识别结果
                    } else {
                        //接收普通消息
                        nextMAV = wechatCommonMsgReceiveService.receiveMsg(docXml);
                    }
                } catch (IOException e) {
                    logger.warn(JDKStackTrace.getJDKStrack(e));
                } catch (DocumentException e) {
                    logger.warn(JDKStackTrace.getJDKStrack(e));
                } catch (Exception e) {
                    logger.warn(JDKStackTrace.getJDKStrack(e));
                }
            }
        }

        return nextMAV;
    }

    /**
     * 回复空字符串
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/noReply.do")
    public String noReply() {
        logger.info(Constants.LOGPRIFIX + "noReply.do.");
        return "";
    }

    /**
     * 处理来自非微信的消息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/warn.do")
    public String warnReply(HttpServletRequest request) {
        logger.info(Constants.LOGPRIFIX + "处理来自非微信的消息.");
        return "warning!!!";
    }

    /**
     * 微信验证url有效性
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/urlValidVerify.do")
    public String urlValidVerify(HttpServletRequest request) {
        String echostr = request.getParameter("echostr");
        logger.info(Constants.LOGPRIFIX + "微信验证url有效性. echostr=" + echostr);
        return echostr;
    }
}
